<template>
  <Form :model="so" :label-width="80">
    <Row :gutter="16">
      <Col span="6">
        <Form.Item label="开发环境">
          <Radio.Group v-model:value="so.env" @change="changeEnv">
            <Radio value="uat">UAT环境</Radio>
            <Radio value="prod">生产环境</Radio>
          </Radio.Group>
        </Form.Item>
      </Col>
      <Col span="8">
        <Form.Item label="分组条件">
          <Checkbox.Group v-model:value="so.groups">
            <Checkbox value="ProcessGroupName">流程组</Checkbox>
            <Checkbox value="ProcessName">流程名称</Checkbox>
            <Checkbox value="ProjectName">项目名称</Checkbox>
          </Checkbox.Group>
        </Form.Item>
      </Col>
      <Col span="3">
        <Form.Item label="猎豹相关">
          <Switch v-model:checked="so.leoOnly" />
        </Form.Item>
      </Col>
      <Col span="4">
        <Form.Item label="年度">
          <Select v-model:value="so.year">
            <Select.Option v-for="item of years" :value="item.value" :key="item.value">{{ item.text }}</Select.Option>
          </Select>
        </Form.Item>
      </Col>
    </Row>
    <Row :gutter="16">
      <Col :span="19">
        <Form.Item label="流程组">
          <Select v-model:value="so.processGroups" :filterOption="filterGroups" :allowClear="true" mode="multiple">
            <Select.Option :value="item.ID" :key="item.ID" v-for="item of processGroups">{{ item.ProcessGroupDisplayName }}</Select.Option>
          </Select>
        </Form.Item>
      </Col>
      <Col style="text-align: right;flex: 1;" class="btn-group">
        <Button shape="round" type="primary" @click="getDetailStatistics()"><SearchOutlined /> 查询</Button>
        <Button shape="round" type="default" @click="exports()"><DownloadOutlined /> 下载</Button>
      </Col>
    </Row>
  </Form>
  <Card size="small" style="margin-top: 10px">
    <Row :gutter="16">
      <Col span="12">
        <h5>已提交的单据统计</h5>
        <Table bordered size="small" :columns="dynamicColumns" :pagination="false" :scroll="{ y: autoHeight }" :data-source="submits"></Table>
      </Col>
      <Col span="12">
        <h5>已审核的单据统计</h5>
        <Table bordered size="small" :columns="dynamicColumns" :pagination="false" :scroll="{ y: autoHeight }" :data-source="audits"></Table>
      </Col>
    </Row>
  </Card>
</template>
<script setup>
  import * as XLSX from 'xlsx';

  import { useStore } from 'vuex';
  import { ref, reactive, inject, onMounted } from 'vue';
  import { Form, Row, Col, Switch, Card, Table, Radio, Button, Select, Checkbox } from 'ant-design-vue';
  import { SearchOutlined, DownloadOutlined } from '@ant-design/icons-vue';

  const $store = useStore();
  const $http = inject('$http');
  const $eventBus = inject('$eventBus');

  const autoHeight = ref(400);
  const years = ref([]);
  const processGroups = ref([]);
  const dynamicColumns = ref([]);
  const submits = ref([]);
  const audits = ref([]);

  const config = reactive({ hosts: [] });
  const so = reactive({
    env: 'prod',
    groups: [],
    year: 'all',
    leoOnly: false,
    processGroups: []
  });

  const columns = [
    { title: '日期', dataIndex: 'YearMonth', width: 100 },
    { title: '数量', dataIndex: 'Counts', width: 100 }
  ];

  function getDetailStatistics() {
    $http.post(`/api/iworkflow/${so.env}/statistics/submitDetails`, so).then(res => {
      submits.value = res.datas;
    });

    $http.post(`/api/iworkflow/${so.env}/statistics/auditDetails`, so).then(res => {
      audits.value = res.datas;
    });

    getDynamicColumns();
  }

  function getDynamicColumns() {
    let rs = [];

    for (let item of so.groups) {
      if (item == 'ProjectName') {
        rs.push({ title: '项目名称', dataIndex: item, width: 200 });
      }

      if (item == 'ProcessName') {
        rs.push({ title: '流程名称', dataIndex: item, width: 200 });
      }

      if (item == 'ProcessGroupName') {
        rs.push({ title: '流程组', dataIndex: item, width: 200 });
      }
    }

    dynamicColumns.value = [
      {
        title: '序号',
        width: 40,
        align: 'center',
        customRender: ({ index }) => index + 1
      },
      ...rs,
      ...columns
    ];
  }

  function getProcessGroup() {
    let requestData = {
      host: config.hosts.find(h => h.env == so.env).url,
      api: '/api/ProcessGroup/GetProcessGroupList',
      data: [
        { name: 'IsDisabled', type: 'query', value: false },
        { name: 'PageSize', type: 'query', value: 20000 }
      ]
    };

    $http.post(`/api/iworkflow/webapi/invoke`, requestData).then(res => {
      if (res.success) {
        processGroups.value.length = 0;

        processGroups.value.push(...res.data.dataList);
      }
    });
  }

  function filterGroups(inputValue, option) {
    let content = option.children[0].children.toLowerCase();

    return content.indexOf(inputValue.toLowerCase()) != -1;
  }

  function changeEnv() {
    so.processGroups = [];

    getProcessGroup();
  }

  function exports() {
    let index = 1;
    let titles = dynamicColumns.value.map(d => d.title);

    let submitDatas = [titles];
    let auditDatas = [titles];

    submits.value.forEach(s => {
      let rs = [index++];

      for (let col of dynamicColumns.value) {
        if (col.dataIndex) {
          rs.push(s[col.dataIndex]);
        }
      }

      submitDatas.push(rs);
    });

    index = 1;
    audits.value.forEach(s => {
      let rs = [index++];

      for (let col of dynamicColumns.value) {
        if (col.dataIndex) {
          rs.push(s[col.dataIndex]);
        }
      }

      auditDatas.push(rs);
    });

    const ws1 = XLSX.utils.aoa_to_sheet(submitDatas, {
      '!cols': [{ width: 120 }, { width: 120 }, { width: 120 }, { width: 120 }]
    });

    const ws2 = XLSX.utils.aoa_to_sheet(auditDatas);
    const wb = XLSX.utils.book_new();

    XLSX.utils.book_append_sheet(wb, ws1, '已提交单据');
    XLSX.utils.book_append_sheet(wb, ws2, '已审批的单据');

    XLSX.writeFile(wb, '单据统计.xlsx');
  }

  function getConfigs() {
    $http.get('/api/iworkflow/webapi/configs/').then(res => {
      config.hosts = reactive(res.hosts);

      getProcessGroup();
    });
  }

  function ResizeDetailPanel(area) {
    autoHeight.value = area.height - 230;
  }

  onMounted(() => {
    let currentYear = new Date().getFullYear();

    years.value.push({ text: '全部', value: 'all' });

    for (let year = currentYear; year >= 2018; year--) {
      years.value.push({ text: year.toString(), value: year.toString() });
    }

    ResizeDetailPanel($store.state.area.content);
    $eventBus.on('windowResizeChanged', client => ResizeDetailPanel(client));

    getConfigs();
    getDetailStatistics();
  });
</script>
<style lang="less" scoped>
  .ant-card-body {
    h5 {
      font-size: 15px;
      font-weight: bolder;
      margin-top: 15px;

      &:first-of-type {
        margin-top: 0;
      }
    }
  }
</style>
